package com.daxt.controller.system;

import java.time.LocalDateTime;
import java.util.List;

import com.daxt.base.common.util.RedisUtil;
import com.daxt.base.common.util.TokenInfo;
import com.daxt.common.annotations.LoginAuth;
import com.daxt.common.annotations.LoginUser;
import com.daxt.mapper.sys.*;
import com.daxt.model.dic.ClientType;
import com.daxt.model.service.archives.result.ArchivesEditResearchResult;
import com.daxt.model.service.archives.vo.ArchivesDoc;
import com.daxt.model.service.archives.vo.ArchivesEditResearch;
import com.daxt.model.service.archives.vo.ArchivesFonds;
import com.daxt.model.service.base.result.UserInfo;
import com.daxt.model.service.base.vo.RoleDept;
import com.daxt.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.daxt.common.result.PageInfo;
import com.daxt.common.result.PageUtil;
import com.daxt.common.result.Result;
import com.daxt.common.result.ResultCode;
import com.daxt.common.result.ResultUtil;
import com.daxt.model.service.base.vo.Role;
import com.daxt.model.service.base.vo.RoleFunction;
import com.daxt.model.service.base.vo.UserRole;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;

@Api(tags = "角色")
@RestController
public class RoleController {


	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RoleDeptMapper roleDeptMapper;
	@Autowired
	private RoleFunctionMapper roleFunctionMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private ArchivesFondsMapper archivesFondsMapper;
	@Autowired
	private UserService userService;
	@ApiOperation(value = "获取角色", notes = "")
	@GetMapping("/role")
	@LoginAuth()
	public Result<PageInfo<Role>> getList(@ApiParam("") @RequestParam(value = "pageNum", required = false) Integer pageNum,
			@ApiParam("") @RequestParam(value = "pageSize", required = false) Integer pageSize,
			@ApiParam("") @RequestParam(value = "roleName", required = false) String roleName,
			@ApiParam("全宗id") @RequestParam(value = "fondsId", required = false) String fondsId,
			@ApiIgnore @LoginUser UserInfo loginUser){
		if (pageNum == null || pageSize == null) {
			pageNum = 1;
			pageSize = 10;
		}
		QueryWrapper<Role> queryWrapper=new QueryWrapper<Role>();
		String userName= loginUser.getUsername();
		String role = loginUser.getRole();
		if(!"admin".equals(userName) && !"超级管理员".equals(role)){
			String fondsId1=loginUser.getFondsId();
			queryWrapper.eq("fondsId",fondsId1);
		}
		queryWrapper.eq(!StringUtils.isEmpty(fondsId),"fondsId",fondsId);
		if(!StringUtils.isEmpty(roleName)) {
			queryWrapper.eq("name", roleName);
		}
		Page<Role> page=new Page<Role>(pageNum,pageSize);;
		IPage<Role> info = roleMapper.selectPage(page, queryWrapper);
		if(info.getRecords().size()>0) {
			for(int i=0;i<info.getRecords().size();i++) {
				String fondsId2 = info.getRecords().get(i).getFondsId();
				if(!StringUtils.isEmpty(fondsId2)){
					String fondsName = archivesFondsMapper.selectById(fondsId2).getFondsName();
					info.getRecords().get(i).setFondsName(fondsName);
				}
			}
		}
		PageInfo<Role> data = PageUtil.data(info.getPages(), info.getSize(), info.getTotal(), info.getRecords());
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, data);
	}
	
	@ApiOperation(value = "添加", notes = "")
	@PostMapping("/role")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> save(@RequestBody Role entity){
		entity.setCreateTime(LocalDateTime.now());
		int rows = roleMapper.insert(entity);
		//配置人员为普通用户
		if( !StringUtils.isEmpty(entity.getFondsId()) && entity.getName().contains("普通用户")){
			userService.buildUserRole(entity);
		}
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}

	@ApiOperation(value = "修改", notes = "")
	@PutMapping("/role")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> edit(@RequestBody Role entity){
		entity.setUpdateTime(LocalDateTime.now());
		int rows = roleMapper.updateById(entity);
		//配置人员为普通用户
		if( !StringUtils.isEmpty(entity.getFondsId()) && entity.getName().contains("普通用户")){
			userService.buildUserRole(entity);
		}
		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}

	@ApiOperation(value = "删除", notes = "")
	@DeleteMapping("/role/{roleId}")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> del(@PathVariable("roleId") String roleId){
		int rows = roleMapper.deleteById(roleId);

		QueryWrapper<UserRole> userRoleQueryWrapper=new QueryWrapper<>();
		userRoleQueryWrapper.eq("roleId",roleId);
		userRoleMapper.delete(userRoleQueryWrapper);


		return ResultUtil.data(rows>0?ResultCode.RESULT_SUCCESS.getCode():ResultCode.RESULT_ERROR.getCode(), null, null);
	}
	
	@ApiOperation(value = "设置用户角色", notes = "")
	@PostMapping("/role/setRoleResouce/{groupId}")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> setUserRole(
			@ApiParam("") @PathVariable("systemId")String systemId,
			@ApiParam("") @RequestBody List<String> groupIds){
		try {
		QueryWrapper<UserRole> wrapper=new QueryWrapper<UserRole>();
		wrapper.eq("userId",systemId);
		userRoleMapper.delete(wrapper);
		for (String string : groupIds) {
			UserRole entity=new UserRole();
			entity.setRoleId(Long.parseLong(string));
			entity.setUserId(Long.parseLong(systemId));
			userRoleMapper.insert(entity);
		}
		String key = TokenInfo.getKey(systemId, ClientType.SSO.getKey());
		redisUtil.del(key);
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
		}
	}

	@ApiOperation(value = "设置角色功能", notes = "")
	@PostMapping("/role/fun")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> saveRoleFun(@RequestBody List<RoleFunction> roleFunctions){
		try {
		if(roleFunctions!=null&&roleFunctions.size()>0) {
		QueryWrapper<RoleFunction> wrapper=new QueryWrapper<RoleFunction>();
		wrapper.eq("roleId",roleFunctions.get(0).getRoleId());
		roleFunctionMapper.delete(wrapper);
		}
		for (RoleFunction roleFunction : roleFunctions) {
			roleFunctionMapper.insert(roleFunction);
		}
		return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
		}
	}


	@ApiOperation(value = "设置角色部门", notes = "")
	@PostMapping("/role/setRoleDept/{groupId}")
	@Transactional(rollbackFor = Exception.class)
	public Result<String> setRoleDept(
			@ApiParam("") @PathVariable("roleId")String roleId,
			@ApiParam("") @RequestBody List<String> groupIds){
		try {
			QueryWrapper<RoleDept> wrapper=new QueryWrapper<RoleDept>();
			wrapper.eq("roleId",roleId);
			roleDeptMapper.delete(wrapper);
			for (String string : groupIds) {
				RoleDept entity = new RoleDept();
				entity.setId(Long.parseLong(roleId));
				entity.setDeptId(Long.parseLong(string));
				roleDeptMapper.insert(entity);
			}
			return ResultUtil.data(ResultCode.RESULT_SUCCESS.getCode(), null, null);
		}catch (Exception e) {
			e.printStackTrace();
			return ResultUtil.data(ResultCode.RESULT_ERROR.getCode(), "操作异常！！！", null);
		}
	}


}
